//
//  ZYCustomizeVC.m
//  YiLin
//
//  Created by Zyark on 2019/1/6.
//  Copyright © 2019 Zyark. All rights reserved.
//

#import "ZYCustomizeVC.h"
#import "EBDropdownListView.h"
#import "ZYCustomTextField.h"
#import "ZYViewUtils.h"
#import "ZYCurveViewModel.h"
#import "ZYCurve.h"
#import "ZYDevice.h"

@interface ZYCustomizeVC ()
@property(nonatomic,strong) NSArray *customValueArray;
@property(nonatomic,strong) UIScrollView *scrollView;
@property(nonatomic,strong) EBDropdownListView *selectListView;
@property(nonatomic,strong) UIView *bgView;
@property(nonatomic,strong) NSArray *textFieldArray;
@property(nonatomic,strong) UIButton *confirmBtn;
/**
 获取曲线值
 */
@property(nonatomic,strong) ZYCurveViewModel *viewModel;

/**当前曲线值*/
@property(nonatomic,strong) NSArray *currentArray;

/**模板*/
@property(nonatomic,strong) NSArray *templateArray;

//@property(nonatomic,strong) 
@end

@implementation ZYCustomizeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTap];
    [self setupView];
    [self bindView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setupTitleView];
    [self.viewModel.getCustomCurveCommand execute:nil];
//    [self.viewModel.curveCommand execute:nil];
}

-(void)setupTitleView{
    UIView *bgView = [[UIView alloc] init];
    bgView.size = CGSizeMake(ZYSCREEN_W  * 0.7, GetRectNavAndStatusHight);
    
    UILabel *leftTitleLabel = [[UILabel alloc] init];
    leftTitleLabel.textColor = [UIColor whiteColor];
    leftTitleLabel.font = [UIFont systemFontOfSize:20];
    leftTitleLabel.textAlignment = NSTextAlignmentRight;
    
//    UILabel *rightTitleLabel = [[UILabel alloc] init];
//    rightTitleLabel.textColor = [UIColor whiteColor];
//    rightTitleLabel.font = [UIFont systemFontOfSize:13];
//    rightTitleLabel.textAlignment = NSTextAlignmentLeft;
    
//    titleLabel.text = _store.name;
    NSString *controllerNameLeft = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_CUSTOM_SETTINGS_CONTROLLER_TITLE];
    NSString *controllerNameRight = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_CUSTOM_SETTINGS_PROGRAMMING_TITLE];
    NSString *title = [NSString stringWithFormat:@"%@%@",controllerNameLeft,controllerNameRight];
    NSRange leftRange = [title rangeOfString:[NSString stringWithFormat:@"%@",controllerNameLeft]];
    NSRange rightRange = [title rangeOfString:[NSString stringWithFormat:@"%@",controllerNameRight]];
    NSMutableAttributedString *mastring = [[NSMutableAttributedString alloc] initWithString:title attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20.0f]}];
    mastring.color = [UIColor whiteColor];
    //解决富文本文字大小不一，文字无法垂直局中的问题
    NSMutableParagraphStyle *ParagraphStyle =  [[NSMutableParagraphStyle alloc] init];
    ParagraphStyle.lineHeightMultiple = 1;
    ParagraphStyle.lineSpacing = 0;
    ParagraphStyle.paragraphSpacing = 0;
    ParagraphStyle.paragraphSpacingBefore = 0;
    NSDictionary *rightDict = @{NSFontAttributeName:[UIFont systemFontOfSize:13],
                           NSBaselineOffsetAttributeName:@(([UIFont systemFontOfSize:20].lineHeight - [UIFont systemFontOfSize:13].lineHeight)/2 + (([UIFont systemFontOfSize:20].descender - [UIFont systemFontOfSize:13].descender))),
                           NSParagraphStyleAttributeName:ParagraphStyle
                           };
    
    [mastring addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:leftRange];
    [mastring addAttributes:rightDict range:rightRange];
    [bgView addSubview:leftTitleLabel];
    leftTitleLabel.attributedText = mastring;
    [leftTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgView);//.offset(imageSize.width);
        make.centerY.equalTo(bgView);
    }];
    self.navigationItem.titleView = bgView;
    
}

-(void)setupView{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ZYSCREEN_H - self.navigationView.bottom - SafeAreaBottomHeight)];
    _scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_scrollView];
    _scrollView.alwaysBounceHorizontal = NO;
    _scrollView.alwaysBounceVertical = YES;
    _scrollView.top = self.navigationView.bottom;
    _scrollView.left = 0;
    if (@available(iOS 11.0, *)) {
        _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
//    [self setupLeftListView];
    [self setupTextFieldViews];
    [self setupConfirmBtn];
    _scrollView.contentSize = CGSizeMake(0, _confirmBtn.bottom + 10 + SafeAreaBottomHeight);
    
}

-(void)setupLeftListView{
    _selectListView = [[EBDropdownListView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W - 30, 36) isCustomize:YES];
    _selectListView.backgroundColor = [UIColor clearColor];
    _selectListView.font = [UIFont systemFontOfSize:14];
    _selectListView.textColor = kLabelColor;
    _selectListView.selectTextColor = kMainColor;
    _selectListView.arrowImgName = @"ic_curve_customize_select";
    _selectListView.layer.borderColor = kMainColor.CGColor;
    _selectListView.layer.borderWidth = 1;
    @weakify(self);
    [_selectListView setDropdownListViewSelectedBlock:^(EBDropdownListView *dropdownListView) {
        @strongify(self);
        NSInteger index = dropdownListView.selectedIndex;
        if(index == 0){//未选择
            self.currentArray = self.customValueArray;
            [self setupCurrentValue];
            return;
        }
        if((index - 1 ) < [self.templateArray count]){
            self.currentArray = [self.templateArray objectAtIndex:index - 1];
            [self setupCurrentValue];
        }
    }];
    [_scrollView addSubview:_selectListView];
    _selectListView.top = 0;
    _selectListView.centerX = _scrollView.width / 2;
    _selectListView.dataSource = [self setupSelectArray];
}

-(NSArray *)setupSelectArray{
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    NSArray *titleArray = @[[language getStringByKey:LC_CURVE_TYPE_LABEL_LOAD_TEMPLATE],
                            [language getStringByKey:LC_CURVE_TYPE_LABEL_AUTOMATIC_LEARNING],
                            [language getStringByKey:LC_CURVE_TYPE_LABEL_ELDERLY_CHILDREN],
                            [language getStringByKey:LC_CURVE_TYPE_SOUTH],
                            [language getStringByKey:LC_CURVE_TYPE_NORTH]];
    NSArray *curveTypeArray = @[@-1,
                                [NSNumber numberWithUnsignedInteger:ZYCurveTypeAutomaticLearning],
                                [NSNumber numberWithUnsignedInteger:ZYCurveTypeElderlyChildren],
                                [NSNumber numberWithUnsignedInteger:ZYCurveTypeSouth],
                                [NSNumber numberWithUnsignedInteger:ZYCurveTypeNorth]];
    NSInteger count = 0;
    NSMutableArray *dataSource = [NSMutableArray arrayWithCapacity:[titleArray count]];
    for (NSString *title in titleArray) {
        NSInteger type = [[curveTypeArray objectAtIndex:count] integerValue];
        EBDropdownListItem *item = [[EBDropdownListItem alloc] initWithItem:[NSString stringWithFormat:@"%ld",type] itemName:title];
        [dataSource addObject:item];
        count ++;
    }
    return dataSource;
}

-(void)setupTextFieldViews{
    _bgView = [[UIView alloc] init];
    _bgView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_bgView];
    int cell = 0;
    int row = 0;
    CGFloat height = 30;
    CGFloat width = ZYSCREEN_W / 2;
    CGFloat bottom = 0;
    NSMutableArray *textFieldArray = [NSMutableArray array];
    for(int i=0;i<=23;i++){
        NSString *leftTitle = @"";
        if(i < 10){
            leftTitle = [NSString stringWithFormat:@"0%dh",i];
        }else{
            leftTitle = [NSString stringWithFormat:@"%dh",i];
        }
        ZYCustomTextField *field = [[ZYCustomTextField alloc] initWithFrame:CGRectMake(row * width, cell * height, width, height)];
        field.title = leftTitle;
        [_bgView addSubview:field];
        [textFieldArray addObject:field];
        bottom = field.bottom;
        row ++;
        if(row == 2){
            row = 0;
            cell ++;
        }
    }
    _textFieldArray = [textFieldArray copy];
    _bgView.size = CGSizeMake(ZYSCREEN_W, 360);
    _bgView.top = 10;
    _bgView.left = 0;
}

-(void)setupConfirmBtn{
    _confirmBtn = [ZYViewUtils setupConfirmBtn];
    [_scrollView addSubview:_confirmBtn];
    _confirmBtn.centerX = self.view.centerX;
    _confirmBtn.top = _bgView.bottom + 25;
    [_confirmBtn addTarget:self action:@selector(doConfirm) forControlEvents:UIControlEventTouchUpInside];
    [_confirmBtn setTitle:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_FINISH_SETTING_BUTTON_TITLE] forState:UIControlStateNormal];
}

-(void)bindView{
    [self bindCurve];
    [self bindSetCustomCurve];
    [self bindGetCustomCurve];
}

-(void)bindCurve{
    @weakify(self);
    [[self.viewModel.curveCommand.executionSignals switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        [self setupData:x];
    }];
}

-(void)bindSetCustomCurve{
    @weakify(self);
    [[self.viewModel.setCustomCurveCommand.executionSignals switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        [[ToastHelper sharedToastHelper] toast:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_SET_SUCCESS]];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [self.viewModel.setCustomCurveCommand.errors subscribeNext:^(id x) {
        [ZYBasicHelper handleErrorMessaeWithError:x message:nil controller:self];
    }];
}

-(void)bindGetCustomCurve{
    @weakify(self);
    [[self.viewModel.getCustomCurveCommand.executionSignals switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        ZYCurve *curve = x;
        NSString *value = curve.value;
        NSArray *valueArray = [value componentsSeparatedByString:@","];
        self.customValueArray = valueArray;
        self.currentArray = valueArray;
        [self setupCurrentValue];
    }];
}

-(void)setupCurrentValue{
    int item = 0;
//    for (NSString *value in self.currentArray) {
//        if(!self.textFieldArray || [self.textFieldArray count] <= item){
//            return;
//        }
//        ZYCustomTextField *field = [self.textFieldArray objectAtIndex:item];
//        [field setTextFieldValue:value];
//        item ++;
//    }
    for ( ZYCustomTextField *field in self.textFieldArray) {
        if(item != 0){
            [field setTextFieldValue:@""];
            if(!self.currentArray || [self.currentArray count] <= item){
                continue;
            }
            NSString *value = [self.currentArray objectAtIndex:item - 1];
            [field setTextFieldValue:value];
        }else{
            ZYCustomTextField *first = [self.textFieldArray firstObject];
            NSString *value = [self.currentArray lastObject];
            [first setTextFieldValue:value];
        }
        item ++;
    }
}

-(void)setupData:(NSArray *)array{
    NSMutableArray *item1Array = [NSMutableArray array];//自动学习
    NSMutableArray *item2Array = [NSMutableArray array];//老人小孩
    NSMutableArray *item3Array = [NSMutableArray array];//南方曲线
    NSMutableArray *item4Array = [NSMutableArray array];//北方曲线
    for (ZYCurve *curveInfo in array) {
        if(curveInfo.deviceType != _device.serverDeviceType){
            continue;
        }
        if(_device.type == ZYDeviceTypeRadiantFloorHeating){
            curveInfo.type = curveInfo.type - 4;
        }
        NSArray *valueArray = [curveInfo.value componentsSeparatedByString:@","];
        switch (curveInfo.type) {
            case ZYCurveTypeAutomaticLearning:
                [item1Array addObjectsFromArray:valueArray];
                break;
            case ZYCurveTypeElderlyChildren:
                [item2Array addObjectsFromArray:valueArray];
                break;
            case ZYCurveTypeSouth:
                [item3Array addObjectsFromArray:valueArray];
                break;
            case ZYCurveTypeNorth:
                [item4Array addObjectsFromArray:valueArray];
                break;
                
            default:
                break;
        }
    }
    _templateArray = @[item1Array,item2Array,item3Array,item4Array];
}

#pragma - 确认
-(void)doConfirm{
    NSMutableArray *valueArray = [NSMutableArray array];
    int i = 0;
    for ( ZYCustomTextField *field in self.textFieldArray) {
        if(i != 0){
            [valueArray addObject:[field getTextFieldValue]];
        }
        i++;
    }
    ZYCustomTextField *field = [self.textFieldArray firstObject];
    [valueArray addObject:[field getTextFieldValue]];
    self.viewModel.valueArray = [valueArray copy];
    [self.viewModel.setCustomCurveCommand execute:nil];
}

-(ZYCurveViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[ZYCurveViewModel alloc] init];
        _viewModel.macAddress = _device.mac;
    }
    return _viewModel;
}

@end
